import axios, { AxiosResponse, AxiosRequestConfig } from "axios";
import { storeToRefs } from "pinia";
import { loginStore } from "@/store/login";
import { showFailToast } from "vant";
import httpEnums from "@/constant/httpEnums";
import { getEnvValue } from "@/utils/index";
import { apiLogout } from "@/api/loginApi";
import {
  encryptBase64,
  encryptWithAes,
  generateAesKey,
  decryptWithAes,
  decryptBase64,
} from "@/utils/crypto";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import { useRouter } from "vue-router";
import isLoading from './loading'
const encryptHeader = "encrypt-key";
(axios as any).defaults.headers["Content-Type"] =
  "application/json;charset=utf-8";
(axios as any).defaults.headers["clientid"] =
  "e5cd7e4891bf95d1d19206ce24a7b32e";
// create an axios instance
const request = axios.create({
  baseURL: getEnvValue("VITE_APP_BASE_API"),
  timeout: 30000,
});

const login = loginStore();
const router = useRouter();

const requestArr = [request];

// 一段时间内的提示显示的防抖，防抖时间设置为5秒
let errMsgDebounceTimer: any = null;
const errMsgDebounceWait = 5000;
// 定时器提示报错的防抖
const errorDebounceHandler = (errorMessage: string) => {
  if (errMsgDebounceTimer) clearTimeout(errMsgDebounceTimer);
  const callNow = !errMsgDebounceTimer;
  errMsgDebounceTimer = setTimeout(() => {
    errMsgDebounceTimer = null;
  }, errMsgDebounceWait);

  if (callNow) {
    // showNotify({
    //   message: errorMessage,
    //   type: "danger",
    //   duration: errMsgDebounceWait,
    // });
    showFailToast({ message: errorMessage });
  }
};
requestArr.forEach((service) => {
  const store = loginStore();
  const { token } = storeToRefs(store);
  // request interceptor
  service.interceptors.request.use(
    async (config: any) => {
      isLoading(1, config.url)
      // 是否需要加密
      const isEncrypt = (config.headers || {}).isEncrypt === "true";
      if (token.value) {
        config.headers!.Authorization = `Bearer ${token.value}`;
      }
      // 当开启参数加密
      if (isEncrypt && (config.method === "post" || config.method === "put")) {
        // 生成一个 AES 密钥
        const aesKey = generateAesKey();
        config.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
        config.data =
          typeof config.data === "object"
            ? encryptWithAes(JSON.stringify(config.data), aesKey)
            : encryptWithAes(config.data, aesKey);
      }
      return config;
    },
    (error) => {
      // do something with request error
      console.warn(error); // for debug
      return Promise.reject(error);
    }
  );

  // response interceptor
  service.interceptors.response.use(
    async (response: any) => {

      // 加密后的 AES 秘钥
      const keyStr = response.headers[encryptHeader];
      // 加密
      if (keyStr != null && keyStr != "") {
        const data = response.data;
        // 请求体 AES 解密
        const base64Str = decrypt(keyStr);
        // base64 解码 得到请求头的 AES 秘钥
        const aesKey = decryptBase64(base64Str.toString());
        // aesKey 解码 data
        const decryptData = decryptWithAes(data, aesKey);
        // 将结果 (得到的是 JSON 字符串) 转为 JSON
        response.data = JSON.parse(decryptData);
      }
      const res = response.data;
      const statusCode = res.code || response.status;
      isLoading(2, response.config.url)
      // blob文件流
      if (res instanceof Blob) {
        return res;
      }

      // 成功
      if (statusCode === httpEnums.CODES.Success) {
        return res;
      }

      // 日志码
      if (statusCode === httpEnums.HTTP_STATUS.MESSAGE.Continue) {
        showFailToast({ message: res.msg });
        return res;
      }

      // 白名单
      if (httpEnums.ERRCODE_WHITE_LIST.indexOf(statusCode) !== -1) {
        return res
      }


      // // token失效
      // if (statusCode === httpEnums.CODES.UnAuthorized) {
      //   return Promise.reject(new Error("token过期！"));
      // }

      const errMsg = res.message || res.msg;

      // showNotify({
      //   message: errMsg || "Error",
      //   type: "danger",
      //   duration: 5 * 1000,
      // });
      showFailToast({ message: errMsg || "Error" });
      if (statusCode == 401) {
        errorDebounceHandler("登录状态已过期，重新登录");
        await apiLogout();
        login.resetToken();
        location.href = "/login";
      }
      // return Promise.reject(new Error(errMsg || "Error"));
      return Promise.reject(errMsg);
    },
    async (error) => {
      isLoading(2, error.config.url)
      if (error.message.indexOf('timeout') > -1) {
        console.warn("err", error, error.message.indexOf('timeout')); // for debugß
        return Promise.reject('timeout');
      }

      const errorData = error.response.data;
      const errorStatus = error.response.status;

      if (errorStatus === httpEnums.HTTP_STATUS.REQUEST_ERROR.UnAuthorized) {
        errorDebounceHandler(error.message);
      } else if (
        errorData.code ===
        httpEnums.HTTP_STATUS.SERVER_ERROR.InternalServerError
      ) {
        // 500特殊处理
        if (error.length > 60) {
          return Promise.reject('请刷新重试');
        } else {
          return Promise.reject(error);
        }
      } else {
        errorDebounceHandler(error.message);

        return Promise.reject(error);
      }
    }
  );
});

export { request };
